import { apiInterceptors, createRole, deleteRole, getAppList, getMenuTree, getRoleList, updateRole } from '@/client/api';
import { Button, Form, Input, Modal, Select, Space, Table, Tag, Tree, message } from 'antd';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { MenuInfo, PaginationResult, RoleInfo, RoleRequest } from '@/client/api/auth';
import type { DataNode } from 'antd/es/tree';
import type { IApp } from '@/types/app';

const RoleManagement = () => {
  const { t } = useTranslation();
  const [roles, setRoles] = useState<PaginationResult<RoleInfo>>({
    items: [],
    total_count: 0,
    total_pages: 0,
    page: 1,
    page_size: 20,
  });
  const [menuTree, setMenuTree] = useState<DataNode[]>([]);
  const [appList, setAppList] = useState<IApp[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<RoleInfo | null>(null);
  const [checkedMenuKeys, setCheckedMenuKeys] = useState<React.Key[]>([]);
  const [selectedAppCodes, setSelectedAppCodes] = useState<string[]>([]);
  const [form] = Form.useForm();

  // 转换菜单树数据
  const convertMenuToTreeData = (menus: MenuInfo[]): DataNode[] => {
    return menus.map(menu => ({
      key: menu.id,
      title: menu.menu_name,
      children: menu.children ? convertMenuToTreeData(menu.children) : undefined,
    }));
  };

  // 加载角色列表
  const loadRoles = async (page = 1, pageSize = 20) => {
    setLoading(true);
    try {
      const [, data] = await apiInterceptors(getRoleList({ page, page_size: pageSize }));
      if (data) {
        setRoles(data);
      }
    } catch (error) {
      message.error(t('load_failed') || '加载失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载菜单树
  const loadMenuTree = async () => {
    try {
      const [, data] = await apiInterceptors(getMenuTree());
      console.log('Role management - Menu tree API response:', data);
      
      // 后端返回格式: Result.succ(menus) -> data就是菜单数组
      if (data && Array.isArray(data)) {
        const treeData = convertMenuToTreeData(data);
        console.log('Role management - Converted tree data:', treeData);
        setMenuTree(treeData);
      } else {
        console.warn('Role management - Invalid menu data:', data);
        message.warning('加载菜单树失败,数据格式不正确');
      }
    } catch (error) {
      console.error('Load menu tree failed:', error);
      message.error('加载菜单树失败');
    }
  };

  // 加载应用列表
  const loadAppList = async () => {
    try {
      const [, data] = await apiInterceptors(getAppList({ page: 1, page_size: 100, published: 'true' }));
      if (data && data.app_list) {
        setAppList(data.app_list);
      }
    } catch (error) {
      console.error('Load app list failed:', error);
    }
  };

  useEffect(() => {
    loadRoles();
    loadMenuTree();
    loadAppList();
  }, []);

  // 打开新增/编辑弹窗
  const handleAdd = () => {
    setEditingRole(null);
    setCheckedMenuKeys([]);
    setSelectedAppCodes([]);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: RoleInfo) => {
    setEditingRole(record);
    form.setFieldsValue({
      role_code: record.role_code,
      role_name: record.role_name,
      role_desc: record.role_desc,
      status: record.status,
      remark: record.remark,
    });
    setCheckedMenuKeys(record.menus?.map(m => m.id) || []);
    setSelectedAppCodes((record as any).app_codes || []);
    setModalVisible(true);
  };

  // 删除角色
  const handleDelete = (record: RoleInfo) => {
    Modal.confirm({
      title: t('confirm_delete') || '确认删除',
      content: `${t('confirm_delete_role') || '确定要删除角色'} "${record.role_name}" ${t('question_mark') || '吗？'}`,
      okText: t('confirm') || '确定',
      cancelText: t('cancel') || '取消',
      onOk: async () => {
        try {
          const [error] = await apiInterceptors(deleteRole(record.id));
          if (!error) {
            message.success(t('delete_success') || '删除成功');
            loadRoles(roles.page, roles.page_size);
          }
        } catch (error) {
          message.error(t('delete_failed') || '删除失败');
        }
      },
    });
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const roleData: RoleRequest = {
        ...values,
        id: editingRole?.id,
        menu_ids: checkedMenuKeys.map(key => Number(key)),
        app_codes: selectedAppCodes,
      } as any;

      if (editingRole) {
        // 更新角色
        const [error] = await apiInterceptors(updateRole(editingRole.id, roleData));
        if (!error) {
          message.success(t('update_success') || '更新成功');
          setModalVisible(false);
          loadRoles(roles.page, roles.page_size);
        }
      } else {
        // 新增角色
        const [error] = await apiInterceptors(createRole(roleData));
        if (!error) {
          message.success(t('create_success') || '创建成功');
          setModalVisible(false);
          loadRoles(roles.page, roles.page_size);
        }
      }
    } catch (error) {
      console.error('Form validation failed:', error);
    }
  };

  const columns = [
    {
      title: '角色编码',
      dataIndex: 'role_code',
      key: 'role_code',
      width: 150,
    },
    {
      title: '角色名称',
      dataIndex: 'role_name',
      key: 'role_name',
      width: 150,
    },
    {
      title: '角色描述',
      dataIndex: 'role_desc',
      key: 'role_desc',
      width: 250,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>{status === 1 ? '启用' : '禁用'}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'gmt_created',
      key: 'gmt_created',
      width: 160,
      render: (time: string) => (time ? new Date(time).toLocaleString() : '-'),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right' as const,
      render: (_: any, record: RoleInfo) => (
        <Space>
          <Button type="link" size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" size="small" danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={handleAdd}>
          {t('add_role') || '新增角色'}
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={roles.items}
        rowKey="id"
        loading={loading}
        scroll={{ x: 1000 }}
        pagination={{
          current: roles.page,
          pageSize: roles.page_size,
          total: roles.total_count,
          onChange: (page, pageSize) => loadRoles(page, pageSize),
          showSizeChanger: true,
          showTotal: total => `共 ${total} 条`,
          position: ['bottomLeft'],
        }}
      />

      <Modal
        title={editingRole ? t('edit_role') || '编辑角色' : t('add_role') || '新增角色'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={700}
        okText={t('confirm') || '确定'}
        cancelText={t('cancel') || '取消'}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 20 }}>
          <Form.Item
            label={t('role_code') || '角色编码'}
            name="role_code"
            rules={[
              { required: true, message: t('please_input_role_code') || '请输入角色编码' },
              { min: 2, max: 50, message: t('role_code_length_error') || '角色编码长度2-50个字符' },
            ]}
          >
            <Input placeholder={t('please_input_role_code') || '请输入角色编码'} disabled={!!editingRole} />
          </Form.Item>

          <Form.Item
            label={t('role_name') || '角色名称'}
            name="role_name"
            rules={[
              { required: true, message: t('please_input_role_name') || '请输入角色名称' },
              { min: 2, max: 100, message: t('role_name_length_error') || '角色名称长度2-100个字符' },
            ]}
          >
            <Input placeholder={t('please_input_role_name') || '请输入角色名称'} />
          </Form.Item>

          <Form.Item label={t('role_desc') || '角色描述'} name="role_desc">
            <Input.TextArea rows={2} placeholder={t('please_input_role_desc') || '请输入角色描述'} />
          </Form.Item>

          <Form.Item label="菜单权限" required>
            <div style={{ border: '1px solid #d9d9d9', borderRadius: 4, padding: 12, maxHeight: 300, overflow: 'auto' }}>
              {menuTree.length > 0 ? (
                <Tree
                  checkable
                  treeData={menuTree}
                  checkedKeys={checkedMenuKeys}
                  onCheck={(checkedKeysValue: any) => {
                    // checkedKeysValue可能是数组或对象{checked: [], halfChecked: []}
                    const keys = Array.isArray(checkedKeysValue) ? checkedKeysValue : checkedKeysValue.checked;
                    setCheckedMenuKeys(keys);
                  }}
                />
              ) : (
                <div style={{ textAlign: 'center', color: '#999', padding: 20 }}>暂无菜单数据</div>
              )}
            </div>
          </Form.Item>

          <Form.Item label="应用权限" tooltip="选择该角色可以访问的应用">
            <Select
              mode="multiple"
              placeholder="请选择可访问的应用（不选则可访问全部）"
              value={selectedAppCodes}
              onChange={setSelectedAppCodes}
              style={{ width: '100%' }}
              showSearch
              filterOption={(input, option) => {
                const label = option?.label || option?.children;
                if (typeof label === 'string') {
                  return label.toLowerCase().includes(input.toLowerCase());
                }
                return false;
              }}
            >
              {appList.map(app => (
                <Select.Option key={app.app_code} value={app.app_code}>
                  {app.app_name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label={t('Status') || '状态'} name="status" initialValue={1}>
            <Select>
              <Select.Option value={1}>{t('active') || '启用'}</Select.Option>
              <Select.Option value={0}>{t('disabled') || '禁用'}</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label={t('Remark') || '备注'} name="remark">
            <Input.TextArea rows={2} placeholder={t('please_input_remark') || '请输入备注'} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleManagement;
